#include "mqueue_communicate.h"

int mqueue_init(char *mp_path,char r_l){

    switch (r_l)
    {
        case 'r':
            // 初始化队列属性
            global_R_attr.mq_flags = 0;
            global_R_attr.mq_maxmsg = MAX_MSG_NUM;//最大信息条数
            global_R_attr.mq_msgsize = MAX_MSG_SIZE;//消息大小
            global_R_attr.mq_curmsgs = 0;//当前缓存数

            // 打开或创建消息队列
            global_R_mq = mq_open(mp_path, O_CREAT | O_RDWR, 0777, &global_R_attr);
            if (global_R_mq == (mqd_t)-1) {
                perror("mq_open");
                exit(1);
            }
            break;
        case 'l':
            // 初始化队列属性
            global_L_attr.mq_flags = 1;
            global_L_attr.mq_maxmsg = MAX_MSG_NUM;
            global_L_attr.mq_msgsize = MAX_MSG_SIZE;
            global_L_attr.mq_curmsgs = 0;

            // 打开或创建消息队列
            global_L_mq = mq_open(mp_path, O_CREAT | O_RDWR, 0777, &global_L_attr);
            if (global_L_mq == (mqd_t)-1) {
                perror("mq_open");
                exit(1);
            }
            break;
        
        default:
            break;
    }

    return 0;
}

int mqueue_send(char r_l,char *data,int size){

    switch (r_l)
    {
        case 'r':
            if (mq_send(global_R_mq, data, size, 0) == -1) {
                perror("mq_send");
                exit(-1);
            }
            break;
        case 'l':
            if (mq_send(global_L_mq, data, size, 0) == -1) {
                perror("mq_send");
                exit(-1);
            }
            break;
        
        default:
            break;
    }

    return 0;
}

char* mqueue_receive(char r_l){
    char buffer[1280];
    unsigned int priority;

    switch (r_l)
    {
        case 'r':
            if (mq_receive(global_R_mq, buffer, sizeof(buffer), &priority) == -1) {
                perror("R:mq_receive");
                exit(-1);
            }
            break;
        case 'l':
            if (mq_receive(global_L_mq, buffer, sizeof(buffer), &priority) == -1) {
                perror("L:mq_receive");
                exit(-1);
            }
            break;
        
        default:
            return -1;
            break;
    }

    printf("Received message: %s\n", buffer);
}

int mqueue_cloes(char r_l){

    switch (r_l)
    {
        case 'r':
            mq_close(global_R_mq);
            break;
        case 'l':
            mq_close(global_L_mq);
            break;
        default:
            printf(">>> mqueue_cloes parameter error!!!\n\r");
            return -1;
            break;
    }
    return 0;
}

int mqueue_delete(char r_l){

    switch (r_l)
    {
        case 'r':
            mq_unlink(MQUEUE_R_PATH);
            break;
        case 'l':
            mq_unlink(MQUEUE_R_PATH);
            break;
        default:
            printf(">>> mqueue_delete parameter error!!!\n\r");
            return -1;
            break;
    }

    return 0;
}





